{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LCM(42, 39) =  546\n",
      "LCM(48, -28) =  336\n"
     ]
    }
   ],
   "source": [
    "# 最小公倍数\n",
    "def lcm(a, b):\n",
    "    a, b = abs(a), abs(b)  # abs() 返回一个数的绝对值\n",
    "    if a == b:\n",
    "        return a\n",
    "    if a < b :\n",
    "        a, b = b, a  # 保证 a > b\n",
    "        \n",
    "    result = 1\n",
    "    for i in range(1, b + 1):\n",
    "        c = a * i\n",
    "        if c % b == 0:\n",
    "            result = c\n",
    "            break\n",
    "            \n",
    "    return result\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    print('LCM(42, 39) = ', lcm(42, 39))\n",
    "    print('LCM(48, -28) = ', lcm(48, -28))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LCM(42, 39) =  546.0\n"
     ]
    }
   ],
   "source": [
    "# 利用最大公约数求最小公倍数\n",
    "# 因为\n",
    "# ab = GCD(a, b)LCM(a, b)\n",
    "\n",
    "import math\n",
    "def lcm_by_gcd(a, b):\n",
    "    a, b = abs(a), abs(b)\n",
    "    \n",
    "    return a if a == b else (a * b ) / math.gcd(a, b)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "      print('LCM(42, 39) = ', lcm_by_gcd(42, 39))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
